#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
全自动化工作流程模块
实现录音→转文本→生成摘要→推送飞书的完整自动化流程
"""

import os
import json
import time
import subprocess
from datetime import datetime
from pathlib import Path

from config import get_config
from speech_recognition import SpeechRecognizer
from llm_processor import LLMProcessor

class AutomationWorkflow:
    """自动化工作流程管理器"""
    
    def __init__(self):
        """初始化工作流程"""
        self.config = get_config()
        self.speech_recognizer = None
        self.llm_processor = None
        
        # 初始化各个组件
        self._initialize_components()
    
    def _initialize_components(self):
        """初始化各个处理组件"""
        try:
            # 初始化语音识别器
            if self.config.SPEECH_API_TOKEN and self.config.SPEECH_API_URL:
                self.speech_recognizer = SpeechRecognizer(
                    api_key=self.config.SPEECH_API_TOKEN,
                    api_url=self.config.SPEECH_API_URL
                )
                print("✓ 语音识别器初始化成功")
            else:
                print("✗ 语音识别器初始化失败：缺少SPEECH_API_TOKEN或SPEECH_API_URL")
            
            # 初始化大模型处理器
            if all([self.config.LLM_API_KEY, self.config.LLM_BASE_URL, self.config.LLM_MODEL_NAME]):
                self.llm_processor = LLMProcessor(
                    api_key=self.config.LLM_API_KEY,
                    base_url=self.config.LLM_BASE_URL,
                    model_name=self.config.LLM_MODEL_NAME
                )
                self.llm_processor.set_temperature(self.config.LLM_TEMPERATURE)
                print("✓ 大模型处理器初始化成功")
            else:
                print("✗ 大模型处理器初始化失败：缺少必要的API配置")
                
        except Exception as e:
            print(f"组件初始化异常: {str(e)}")
    
    def process_audio_file(self, audio_file_path, auto_push=None):
        """
        处理单个音频文件的完整流程
        
        Args:
            audio_file_path (str): 音频文件路径
            auto_push (bool): 是否自动推送到飞书，None则使用配置文件设置
            
        Returns:
            dict: 处理结果
        """
        if auto_push is None:
            auto_push = self.config.AUTO_PUSH_TO_FEISHU
        
        print(f"\n{'='*50}")
        print(f"开始处理音频文件: {os.path.basename(audio_file_path)}")
        print(f"{'='*50}")
        
        # 生成文件名（基于音频文件名）
        base_name = Path(audio_file_path).stem
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        
        transcript_file = self.config.get_transcript_file_path(f"{base_name}_{timestamp}.json")
        summary_file = self.config.get_summary_file_path(f"{base_name}_{timestamp}.json")
        
        result = {
            "audio_file": audio_file_path,
            "transcript_file": transcript_file,
            "summary_file": summary_file,
            "timestamp": timestamp,
            "steps": {}
        }
        
        try:
            # 步骤1: 语音转文本
            print("\n🎵 步骤1: 语音转文本...")
            if not self.speech_recognizer:
                raise Exception("语音识别器未初始化")
            
            transcript_result = self.speech_recognizer.recognize_file(
                audio_file_path, 
                transcript_file
            )
            
            if transcript_result.get("status") != "success":
                raise Exception(f"语音识别失败: {transcript_result.get('error', '未知错误')}")
            
            transcript_text = transcript_result.get("text", "")
            result["steps"]["speech_recognition"] = {
                "status": "success",
                "text_length": len(transcript_text),
                "file": transcript_file
            }
            print(f"✓ 语音转文本完成，文本长度: {len(transcript_text)} 字符")
            
            # 步骤2: 生成摘要和标题
            print("\n🤖 步骤2: 生成摘要和标题...")
            if not self.llm_processor:
                raise Exception("大模型处理器未初始化")
            
            if not transcript_text.strip():
                raise Exception("转录文本为空，无法生成摘要")
            
            summary_result = self.llm_processor.generate_summary_and_title(
                transcript_text,
                summary_file
            )
            
            if summary_result.get("status") != "success":
                raise Exception(f"摘要生成失败: {summary_result.get('error', '未知错误')}")
            
            result["steps"]["llm_processing"] = {
                "status": "success",
                "title": summary_result.get("title", ""),
                "summary": summary_result.get("summary", ""),
                "summary_length": len(summary_result.get("summary", "")),
                "file": summary_file
            }
            print(f"✓ 摘要和标题生成完成")
            print(f"  标题: {summary_result.get('title', 'N/A')}")
            
            # 步骤3: 推送到飞书
            if auto_push:
                print("\n📤 步骤3: 推送到飞书...")
                push_result = self._push_to_feishu(summary_result, base_name)
                result["steps"]["feishu_push"] = push_result
                
                if push_result.get("status") == "success":
                    print("✓ 飞书推送完成")
                else:
                    print(f"✗ 飞书推送失败: {push_result.get('error', '未知错误')}")
            else:
                print("\n📤 步骤3: 跳过飞书推送（根据配置）")
                result["steps"]["feishu_push"] = {"status": "skipped"}
            
            # 步骤4: 清理临时文件（可选）
            if self.config.DELETE_TEMP_FILES:
                print("\n🗑️ 步骤4: 清理临时文件...")
                self._cleanup_temp_files([transcript_file])
                result["steps"]["cleanup"] = {"status": "success"}
            else:
                result["steps"]["cleanup"] = {"status": "skipped"}
            
            result["status"] = "success"
            print(f"\n✅ 音频文件处理完成: {os.path.basename(audio_file_path)}")
            
        except Exception as e:
            error_msg = f"处理音频文件时发生异常: {str(e)}"
            print(f"\n❌ {error_msg}")
            result["status"] = "error"
            result["error"] = error_msg
        
        return result
    
    def _push_to_feishu(self, summary_data, base_name):
        """
        推送数据到飞书
        
        Args:
            summary_data (dict): 摘要数据
            base_name (str): 基础文件名
            
        Returns:
            dict: 推送结果
        """
        try:
            # 准备推送数据 - 确保只推送干净的title和summary
            title = summary_data.get("title", f"{base_name}_摘要")
            summary = summary_data.get("summary", "")
            
            # 如果summary是列表，转换为格式化字符串
            if isinstance(summary, list):
                summary = "\n".join([f"{i+1}. {item}" for i, item in enumerate(summary)])
            
            # 确保summary是字符串且不包含解析说明
            if isinstance(summary, str):
                # 移除可能的markdown代码块和解析说明
                if "```json" in summary or "### 解析" in summary or "根据录音内容" in summary:
                    summary = "摘要内容格式异常，请检查LLM响应"
            
            push_data = {
                "title": title,
                "summary": summary,
                "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                "source": base_name
            }
            
            print(f"[DEBUG] 准备推送的数据:")
            print(f"  标题: {push_data['title']}")
            print(f"  摘要长度: {len(push_data['summary'])} 字符")
            print(f"  摘要预览: {push_data['summary'][:100]}...")
            
            # 将数据写入临时文件供Node.js脚本使用
            temp_summary_file = os.path.join(self.config.SUMMARIES_DIR, "temp_push_data.json")
            with open(temp_summary_file, 'w', encoding='utf-8') as f:
                json.dump(push_data, f, ensure_ascii=False, indent=2)
            
            # 推送脚本路径
            push_script = os.path.join(self.config.BITABLE_DIR, "快速推送.js")
            
            if not os.path.exists(push_script):
                return {
                    "status": "error",
                    "error": f"推送脚本不存在: {push_script}"
                }
            
            # 执行推送脚本
            print(f"正在执行推送脚本: {push_script}")
            result = subprocess.run(
                ["node", push_script],
                cwd=self.config.BITABLE_DIR,
                capture_output=True,
                text=True,
                encoding='utf-8',  # 明确指定UTF-8编码
                errors='replace',  # 遇到编码错误时替换为占位符
                timeout=60  # 60秒超时
            )
            
            print(f"推送脚本返回码: {result.returncode}")
            print(f"推送脚本标准输出: {result.stdout}")
            print(f"推送脚本错误输出: {result.stderr}")
            
            if result.returncode == 0:
                return {
                    "status": "success",
                    "output": result.stdout,
                    "stderr": result.stderr,
                    "temp_file": temp_summary_file
                }
            else:
                return {
                    "status": "error",
                    "error": f"推送脚本执行失败 (返回码: {result.returncode})",
                    "stdout": result.stdout,
                    "stderr": result.stderr,
                    "temp_file": temp_summary_file
                }
                
        except subprocess.TimeoutExpired:
            return {
                "status": "error",
                "error": "推送脚本执行超时"
            }
        except Exception as e:
            return {
                "status": "error",
                "error": f"推送过程中发生异常: {str(e)}"
            }
    
    def _cleanup_temp_files(self, file_list):
        """
        清理临时文件
        
        Args:
            file_list (list): 要删除的文件列表
        """
        for file_path in file_list:
            try:
                if os.path.exists(file_path):
                    os.remove(file_path)
                    print(f"  删除临时文件: {os.path.basename(file_path)}")
            except Exception as e:
                print(f"  删除文件失败 {file_path}: {str(e)}")
    
    def batch_process_recordings(self, recordings_dir=None):
        """
        批量处理录音目录中的所有音频文件
        
        Args:
            recordings_dir (str): 录音目录路径，None则使用配置的默认目录
            
        Returns:
            list: 处理结果列表
        """
        if recordings_dir is None:
            recordings_dir = self.config.RECORDINGS_DIR
        
        print(f"\n开始批量处理录音目录: {recordings_dir}")
        
        # 支持的音频格式
        audio_extensions = ['.wav', '.mp3', '.m4a', '.flac', '.aac']
        
        # 查找所有音频文件
        audio_files = []
        for ext in audio_extensions:
            audio_files.extend(Path(recordings_dir).glob(f"*{ext}"))
        
        if not audio_files:
            print("未找到任何音频文件")
            return []
        
        print(f"找到 {len(audio_files)} 个音频文件")
        
        results = []
        for i, audio_file in enumerate(audio_files, 1):
            print(f"\n处理进度: {i}/{len(audio_files)}")
            result = self.process_audio_file(str(audio_file))
            results.append(result)
            
            # 处理间隔（避免API调用过于频繁）
            if i < len(audio_files):
                time.sleep(2)
        
        # 统计结果
        success_count = sum(1 for r in results if r.get("status") == "success")
        print(f"\n批量处理完成:")
        print(f"  总文件数: {len(results)}")
        print(f"  成功处理: {success_count}")
        print(f"  处理失败: {len(results) - success_count}")
        
        return results
    
    def get_status(self):
        """
        获取工作流程状态
        
        Returns:
            dict: 状态信息
        """
        return {
            "speech_recognizer_ready": self.speech_recognizer is not None,
            "llm_processor_ready": self.llm_processor is not None,
            "auto_process_enabled": self.config.AUTO_PROCESS_ENABLED,
            "auto_push_enabled": self.config.AUTO_PUSH_TO_FEISHU,
            "recordings_dir": self.config.RECORDINGS_DIR,
            "transcripts_dir": self.config.TRANSCRIPTS_DIR,
            "summaries_dir": self.config.SUMMARIES_DIR
        }

def test_workflow():
    """测试自动化工作流程"""
    workflow = AutomationWorkflow()
    
    print("工作流程状态:")
    status = workflow.get_status()
    for key, value in status.items():
        print(f"  {key}: {value}")
    
    # 如果有测试音频文件，可以进行测试
    test_audio = os.path.join(workflow.config.RECORDINGS_DIR, "test.wav")
    if os.path.exists(test_audio):
        print(f"\n测试处理音频文件: {test_audio}")
        result = workflow.process_audio_file(test_audio, auto_push=False)
        print("测试结果:", json.dumps(result, ensure_ascii=False, indent=2))
    else:
        print(f"\n测试音频文件不存在: {test_audio}")
        print("请将测试音频文件放置在recordings目录下")

if __name__ == "__main__":
    test_workflow()